<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Model\Spec;
use App\Model\SpecValue;
use Illuminate\Http\Request;

/**
 * 规格值管理
 */
class SpecValueController extends Controller
{
    /**
     * 定义模型
     */
    public $model;
    public $specModel;

    /**
     * 定义验证
     */
    public $validate;

    /**
     * 初始化控制器
     */
    public function __construct()
    {
        $this->model = (new SpecValue());
        $this->validate = (new \App\Validate\Admin\SpecValue());
        $this->specModel = (new Spec());
    }

    /**
     * 添加规格值
     */
    public function add_spec_value(Request $request)
    {
        // 获取参数
        $only = ['spec_id', 'spec_value'];
        $params = $request->only($only);
        if ($params) {
            if (!$this->validate->check($params)) {
                $this->error($this->validate->getError());
            }
            if (!$this->specModel->where(['id' => $params['spec_id']])->exists()) {
                $this->error('规格id不存在');
            }
            // 判断规格值是否存在
            if ($specValueId = $this->model->getSpecValueIdByName($params['spec_id'], $params['spec_value'])) {
                return $this->success([
                    'value_id' => (int)$specValueId,
                ]);
            }
            // 添加规则值
            if ($this->model->add($params['spec_id'], $params['spec_value']))
                return $this->success([
                    'value_id' => (int)$this->model['id'],
                ]);
            return $this->error();
        }
        $this->error('参数不能为空');
    }
}
